<?php

namespace app\http\middleware;

use app\common\library\Jwt;
use think\Request;
use think\Response;

class CheckApiToken
{
    public function handle(Request $request, \Closure $next)
    {
        $token = $request->header('Authorization');
        if ($token) {
            // 去掉前缀 "Bearer "
            $token = str_replace('Bearer ', '', $token);
            $data = Jwt::decode($token);
            if ($data) {
                // 将用户信息附加到请求中，供后续使用
                $request->user = $data;
                return $next($request);
            }
        }

        // 如果没有 Token 或 Token 无效，返回错误
        return Response::create(['message' => 'Unauthorized'], 'json', 401);
    }
}
